package com.jijuxie.agent.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jijuxie.agent.domain.Agent;
import com.jijuxie.agent.domain.Customer;
import com.jijuxie.agent.domain.DealRecord;
import com.jijuxie.agent.domain.vo.AgentStatsVO;
import com.jijuxie.agent.service.IAgentService;
import com.jijuxie.common.core.R;
import com.jijuxie.system.domain.SysUserRole;
import com.jijuxie.system.mapper.SysUserRoleMapper;
import org.apache.commons.lang3.StringUtils;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 经纪人管理控制器 处理经纪人认证、客户管理、业绩统计等相关操作
 *
 * @author jijuxie
 */
@RestController
@RequestMapping("/agent")
public class AgentController {

    @Autowired
    private IAgentService agentService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 测试接口 - 验证路由是否正常
     */
    @GetMapping("/test")
    public R<String> test() {
        return R.ok("Agent controller is working!");
    }

    /**
     * 申请成为经纪人
     */
    @PostMapping("/apply")
    public R<Object> apply(@RequestBody Agent agent) {
        return agentService.applyAgent(agent);
    }

    /**
     * 前端获取经纪人列表
     */
    @GetMapping("/publiclist")
    public R<Object> getAgentList(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "12") Integer pageSize) {
        System.out.println("调用经纪人公共列表接口: keyword=" + keyword + ", pageNum=" + pageNum + ", pageSize=" + pageSize);
        try {
            return agentService.getAgentList(keyword, pageNum, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("获取经纪人列表失败: " + e.getMessage());
        }
    }

    /**
     * 经纪人认证申请 提交认证资料,等待后台审核
     *
     * @param agent 经纪人认证信息
     */
    @PostMapping("/certify")
    public R<Void> certify(@RequestBody Agent agent) {
        agentService.certify(agent);
        return R.ok();
    }

    /**
     * 审核经纪人认证 管理员审核经纪人认证申请
     *
     * @param agentId 经纪人ID
     * @param status 审核状态
     * @param remark 审核备注
     */
    @PutMapping("/audit/{agentId}")
    public R<Void> audit(@PathVariable Long agentId, @RequestParam String status, @RequestParam String remark) {
        agentService.audit(agentId, status, remark);
        return R.ok();
    }

    /**
     * 获取经纪人列表
     */
    @GetMapping("/list")
    public R<Page<Agent>> list(Page<Agent> page, Agent agent) {
        return R.ok(agentService.selectAgentPage(page, agent));
    }

    /**
     * 获取经纪人详情
     */
    @GetMapping("/{agentId}")
    public R<Agent> getInfo(@PathVariable Long agentId) {
        try {
            System.out.println("调用获取经纪人详情接口: agentId=" + agentId);
            Agent agent = agentService.getAgentInfo(agentId);
            return R.ok(agent);
        } catch (Exception e) {
            System.err.println("获取经纪人详情失败: " + e.getMessage());
            e.printStackTrace();
            return R.fail("获取经纪人详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取我的经纪人信息
     */
    @GetMapping("/info")
    public R<Agent> getMyInfo() {
        return R.ok(agentService.getMyAgentInfo());
    }

    /**
     * 修改经纪人信息
     */
    @PutMapping
    public R<Void> update(@RequestBody Agent agent) {
        agentService.updateAgent(agent);
        return R.ok();
    }

    /**
     * 获取经纪人业绩统计 统计成交数据和客户数据
     *
     * @param agentId 经纪人ID
     * @return 业绩统计数据
     */
    @GetMapping("/stats/{agentId}")
    public R<AgentStatsVO> getStats(@PathVariable Long agentId) {
        return R.ok(agentService.getAgentStats(agentId));
    }

    /**
     * 获取我的业绩统计
     */
    @GetMapping("/stats")
    public R<AgentStatsVO> getMyStats() {
        return R.ok(agentService.getMyStats());
    }

    /**
     * 添加客户信息 新增潜在客户或意向客户
     *
     * @param customer 客户信息
     */
    @PostMapping("/customer")
    public R<Void> addCustomer(@RequestBody Customer customer) {
        agentService.addCustomer(customer);
        return R.ok();
    }

    /**
     * 更新客户信息
     */
    @PutMapping("/customer")
    public R<Void> updateCustomer(@RequestBody Customer customer) {
        agentService.updateCustomer(customer);
        return R.ok();
    }

    /**
     * 获取客户列表
     */
    @GetMapping("/customer/list")
    public R<Page<Customer>> customerList(Page<Customer> page, Customer customer) {
        return R.ok(agentService.selectCustomerPage(page, customer));
    }

    /**
     * 添加成交记录 记录房源成交信息
     *
     * @param record 成交记录信息
     */
    @PostMapping("/deal")
    public R<Void> addDealRecord(@RequestBody DealRecord record) {
        agentService.addDealRecord(record);
        return R.ok();
    }

    /**
     * 确认成交
     */
    @PutMapping("/deal/confirm/{recordId}")
    public R<Void> confirmDeal(@PathVariable Long recordId) {
        agentService.confirmDeal(recordId);
        return R.ok();
    }

    /**
     * 获取成交记录列表
     */
    @GetMapping("/deal/list")
    public R<Page<DealRecord>> dealList(Page<DealRecord> page, DealRecord record) {
        return R.ok(agentService.selectDealRecordPage(page, record));
    }

    /**
     * 获取经纪人申请审核统计
     * 返回待审核、已通过、已拒绝的数量
     */
    @GetMapping("/review/statistics")
    public R<Map<String, Object>> reviewStatistics() {
        try {
            // 检查用户是否有admin角色
            if(!StpUtil.hasRole("admin")) {
                return R.fail("无操作权限");
            }
            
            // 查询各状态的数量
            long pending = agentService.count(new LambdaQueryWrapper<Agent>().eq(Agent::getStatus, "0"));
            long approved = agentService.count(new LambdaQueryWrapper<Agent>().eq(Agent::getStatus, "1"));
            long rejected = agentService.count(new LambdaQueryWrapper<Agent>().eq(Agent::getStatus, "2"));
            
            Map<String, Object> statsMap = new HashMap<>();
            statsMap.put("pending", pending);
            statsMap.put("approved", approved);
            statsMap.put("rejected", rejected);
            
            return R.ok(statsMap);
        } catch (Exception e) {
            return R.fail("获取统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取经纪人申请列表
     * 可按状态、姓名等筛选
     */
    @GetMapping("/review/list")
    public R<Page<Agent>> reviewList(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "realName", required = false) String realName,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "beginTime", required = false) String beginTime,
            @RequestParam(value = "endTime", required = false) String endTime) {
        try {
            // 检查用户是否有admin角色
            if(!StpUtil.hasRole("admin")) {
                return R.fail("无操作权限");
            }
            
            Page<Agent> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Agent> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (status != null && !status.isEmpty()) {
                queryWrapper.eq(Agent::getStatus, status);
            }
            
            if (realName != null && !realName.isEmpty()) {
                queryWrapper.like(Agent::getRealName, realName);
            }
            
            // 按创建时间排序，最新申请排前面
            queryWrapper.orderByDesc(Agent::getCreateTime);
            
            Page<Agent> result = agentService.page(page, queryWrapper);
            return R.ok(result);
        } catch (Exception e) {
            return R.fail("获取申请列表失败: " + e.getMessage());
        }
    }

    /**
     * 审核通过经纪人申请
     */
    @PostMapping("/review/approve")
    public R<Object> approveApplication(@RequestBody Map<String, Object> params) {
        try {
            // 打印接收到的参数
            System.out.println("接收到的审核通过参数: " + params);
            
            // 检查用户是否有admin角色
            if(!StpUtil.hasRole("admin")) {
                return R.fail("无操作权限");
            }
            
            // 参数检查
            if (params.get("id") == null) {
                return R.fail("缺少必要参数:id");
            }
            
            // 修改参数名，从id获取经纪人ID
            Long agentId = Long.valueOf(params.get("id").toString());
            Long userId = params.get("userId") != null ? Long.valueOf(params.get("userId").toString()) : null;
            
            System.out.println("处理审核通过: agentId=" + agentId + ", userId=" + userId);
            
            // 获取经纪人信息
            Agent agent = agentService.getById(agentId);
            if (agent == null) {
                return R.fail("经纪人信息不存在");
            }
            
            // 更新状态为已通过(1)
            agent.setStatus("1"); // 已通过
            agent.setAuditTime(LocalDateTime.now());
            agent.setAuditorId(StpUtil.getLoginIdAsLong());
            agent.setAuditRemark("审核通过");
            
            agentService.updateById(agent);
            
            // 更改用户角色为经纪人
            try {
                // 获取经纪人角色ID (角色ID为2，对应经纪人角色)
                Long agentRoleId = 2L;

                // 查询用户当前的角色记录
                LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SysUserRole::getUserId, agent.getUserId());
                
                // 使用Autowired注入的userRoleMapper
                SysUserRole userRole = userRoleMapper.selectOne(queryWrapper);
                
                if (userRole != null) {
                    // 如果用户已有角色记录(普通用户role_id=3)，更新为经纪人角色(role_id=2)
                    userRole.setRoleId(agentRoleId);
                    userRoleMapper.updateById(userRole);
                    System.out.println("已将用户ID=" + agent.getUserId() + "的角色从普通用户更新为经纪人角色(roleId=" + agentRoleId + ")");
                } else {
                    // 如果用户没有角色记录，新增一条
                    userRole = new SysUserRole();
                    userRole.setUserId(agent.getUserId());
                    userRole.setRoleId(agentRoleId);
                    userRoleMapper.insert(userRole);
                    System.out.println("已为用户ID=" + agent.getUserId() + "添加经纪人角色(roleId=" + agentRoleId + ")");
                }
            } catch (Exception e) {
                System.err.println("修改用户角色失败: " + e.getMessage());
                e.printStackTrace();
                // 不要因为角色修改失败而影响整个审核流程
            }
            
            return R.ok("审核通过成功");
        } catch (Exception e) {
            // 打印详细错误信息
            e.printStackTrace();
            System.err.println("审核通过失败, 参数: " + params + ", 错误: " + e.getMessage());
            return R.fail("审核失败: " + e.getMessage());
        }
    }

    /**
     * 拒绝经纪人申请
     */
    @PostMapping("/review/reject")
    public R<Object> rejectApplication(@RequestBody Map<String, Object> params) {
        try {
            // 打印接收到的参数
            System.out.println("接收到的拒绝申请参数: " + params);

            // 检查用户是否有admin角色
            if(!StpUtil.hasRole("admin")) {
                return R.fail("无操作权限");
            }
            
            // 参数检查
            if (params.get("id") == null) {
                return R.fail("缺少必要参数:id");
            }
            
            // 修改参数名，从id获取经纪人ID
            Long agentId = Long.valueOf(params.get("id").toString());
            String rejectReason = params.get("rejectReason") != null ? params.get("rejectReason").toString() : "不满足要求";
            
            System.out.println("处理拒绝申请: agentId=" + agentId + ", reason=" + rejectReason);
            
            // 获取经纪人信息
            Agent agent = agentService.getById(agentId);
            if (agent == null) {
                return R.fail("经纪人信息不存在");
            }
            
            // 更新状态为已拒绝(2)
            agent.setStatus("2"); // 已拒绝
            agent.setAuditTime(LocalDateTime.now());
            agent.setAuditorId(StpUtil.getLoginIdAsLong());
            agent.setAuditRemark(rejectReason);
            
            agentService.updateById(agent);
            
            return R.ok("已拒绝申请");
        } catch (Exception e) {
            // 打印详细错误信息
            e.printStackTrace();
            System.err.println("拒绝申请失败, 参数: " + params + ", 错误: " + e.getMessage());
            return R.fail("操作失败: " + e.getMessage());
        }
    }
}
